// 确保Vue已加载
if (typeof Vue === 'undefined') {
    console.error('Vue库未加载成功');
}

// 使用Vue全局对象
const { createApp, ref, onMounted, nextTick } = Vue;

// 生成随机聊天室ID
function generateRoomId() {
    return 'room_' + Math.random().toString(36).substring(2, 10);
}

// 格式化消息内容（支持简单的代码块）
function formatMessage(text) {
    // 将 ```code``` 格式化为代码块
    text = text.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
    // 将换行符转换为<br>
    return text.replace(/\n/g, '<br>');
}

// 创建Vue应用
const app = createApp({
    setup() {
        const roomId = ref(generateRoomId());
        const messages = ref([]);
        const inputMessage = ref('');
        const messagesContainer = ref(null);
        const isLoading = ref(false);
        const eventSourceRef = ref(null);

        // 添加系统消息
        const addSystemMessage = (text) => {
            messages.value.push({
                id: Date.now(),
                sender: 'system',
                text: text
            });
            scrollToBottom();
        };

        // 滚动到消息底部
        const scrollToBottom = () => {
            nextTick(() => {
                if (messagesContainer.value) {
                    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
                }
            });
        };

        // 发送消息
        const sendMessage = () => {
            const messageText = inputMessage.value.trim();
            if (!messageText || isLoading.value) return;

            // 添加用户消息
            messages.value.push({
                id: Date.now(),
                sender: 'user',
                text: messageText
            });

            inputMessage.value = '';
            scrollToBottom();
            isLoading.value = true;

            // 关闭之前的SSE连接
            if (eventSourceRef.value) {
                eventSourceRef.value.close();
                eventSourceRef.value = null;
            }

            // 添加AI正在输入的消息
            const aiMessageId = Date.now() + 1;
            messages.value.push({
                id: aiMessageId,
                sender: 'ai',
                text: '正在输入...',
                isStreaming: true
            });
            scrollToBottom();

            // 建立SSE连接
            const apiUrl = `http://localhost:8080/api/ai/chat?memoryId=${roomId.value}&userMessage=${encodeURIComponent(messageText)}`;
            eventSourceRef.value = new EventSource(apiUrl);

            // 处理SSE事件
            eventSourceRef.value.onmessage = (event) => {
                try {
                    const data = event.data;
                    // 查找AI消息并更新
                    const aiMessageIndex = messages.value.findIndex(msg => msg.id === aiMessageId);
                    if (aiMessageIndex !== -1) {
                        // 如果是首次收到数据，替换"正在输入..."
                        if (messages.value[aiMessageIndex].text === '正在输入...') {
                            messages.value[aiMessageIndex].text = data;
                        } else {
                            // 否则追加内容
                            messages.value[aiMessageIndex].text += data;
                        }
                        scrollToBottom();
                    }
                } catch (error) {
                    console.error('处理SSE消息时出错:', error);
                }
            };

            eventSourceRef.value.onerror = (error) => {
                console.error('SSE连接错误:', error);
                const aiMessageIndex = messages.value.findIndex(msg => msg.id === aiMessageId);
                if (aiMessageIndex !== -1) {
                    messages.value[aiMessageIndex].text = '连接出错，请重试';
                    messages.value[aiMessageIndex].isStreaming = false;
                }
                isLoading.value = false;
                eventSourceRef.value.close();
                eventSourceRef.value = null;
            };

            eventSourceRef.value.onopen = () => {
                console.log('SSE连接已建立');
            };

            eventSourceRef.value.onclose = () => {
                console.log('SSE连接已关闭');
                const aiMessageIndex = messages.value.findIndex(msg => msg.id === aiMessageId);
                if (aiMessageIndex !== -1) {
                    messages.value[aiMessageIndex].isStreaming = false;
                }
                isLoading.value = false;
            };
        };

        // 添加换行（Shift+Enter）
        const addNewline = () => {
            inputMessage.value += '\n';
        };

        // 组件挂载时
        onMounted(() => {
            addSystemMessage('欢迎使用AI编程小助手！请输入您的问题，我会尽力为您解答。');
            console.log(`当前聊天室ID: ${roomId.value}`);
        });

        return {
            roomId,
            messages,
            inputMessage,
            messagesContainer,
            sendMessage,
            addNewline,
            formatMessage
        };
    }
});

app.mount('#app');